package com.wangzeqi.changliaoba.myself;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.exceptions.EaseMobException;
import com.wangzeqi.BmobEntity.PersonEntity;
import com.wangzeqi.cache.AllLruCacheLoad;
import com.wangzeqi.changliaba.dao.UserPage;
import com.wangzeqi.changliaoba.BuildConfig;
import com.wangzeqi.changliaoba.R;
import com.wangzeqi.changliaoba.base.BaseActivity;
import com.wangzeqi.changliaoba.singleton.AllSingleTon;
import com.wangzeqi.changliaoba.util.OSUtils;
import com.wangzeqi.changliaoba.worldlet.circle.ImageFloder;
import com.wangzeqi.custom.ChooseDialog;
import com.wangzeqi.custom.CropHelper;

import org.json.JSONArray;

import java.io.InputStream;
import java.io.File;
import java.util.List;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindCallback;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;
import de.greenrobot.dao.query.QueryBuilder;

import android.view.ViewGroup.LayoutParams;

/**
 * Created by dllo on 16/3/4.
 */
public class PersonalDetailActivity extends BaseActivity implements OnClickListener {
    private TextView TvMyID, personSexTv, personNickTv;
    private ImageView personDetailIcon, my_two_dimension_code;
    private CropHelper mCropHelper;
    private ChooseDialog mDialog;
    private RelativeLayout personNick, personSex;
    private ProgressBar progressBar;
    private Button saveBtn;
    private ImageButton backImage;
    String s = "a";
    QueryBuilder qb = AllSingleTon.getOurInstance().getDaoSession().getUserPageDao().queryBuilder();
    List<UserPage> datas = qb.list();
    String nickName, sex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_detail);
        TvMyID = (TextView) findViewById(R.id.Tv_myID);
        personDetailIcon = (ImageView) findViewById(R.id.person_detail_icon);
        TvMyID.setText(EMChatManager.getInstance().getCurrentUser());
        mCropHelper = new CropHelper(this, OSUtils.getSdCardDirectory() + "/head.png");
        mDialog = new ChooseDialog(this, mCropHelper);
        personDetailIcon.setOnClickListener(this);
        personNick = (RelativeLayout) findViewById(R.id.person_nickname);
        personSex = (RelativeLayout) findViewById(R.id.person_sex);
        personSex.setOnClickListener(this);
        personNick.setOnClickListener(this);
        personNickTv = (TextView) findViewById(R.id.person_nickname_tv);
        personSexTv = (TextView) findViewById(R.id.person_sex_tv);
        saveBtn = (Button) findViewById(R.id.save_me);
        saveBtn.setOnClickListener(this);
        backImage = (ImageButton) findViewById(R.id.back_btn);
        backImage.setOnClickListener(this);
        my_two_dimension_code = (ImageView) findViewById(R.id.my_two_dimension_code);
        my_two_dimension_code.setOnClickListener(this);
        progressBar = new ProgressBar(this);
        getMsg();
    }

    private void getMsg() {
        if (datas != null && datas.size() > 0) {
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).getUsername().equals(EMChatManager.getInstance().getCurrentUser())) {
                    personNickTv.setText(datas.get(i).getNick_name());
                    personSexTv.setText(datas.get(i).getSex());
                }
            }
            if (personNickTv.getText().toString() == null || personSexTv.getText().toString() == null) {
                getBmob();
            }
        } else {
            getBmob();
        }
    }

    private void getBmob() {
        String name = EMChatManager.getInstance().getCurrentUser();
        BmobQuery<UserPage> query = new BmobQuery<UserPage>();
        //查询username 是当前用户的数据
        query.addWhereEqualTo("username", name);
        //如果不加上这条语句，默认返回10条数据
        query.setLimit(1);
        query.findObjects(this, new FindListener<UserPage>() {
            @Override
            public void onSuccess(List<UserPage> list) {
                for (UserPage userPage : list) {
                    //获得昵称的信息
                    personNickTv.setText(userPage.getNick_name());
                    //获得性别的信息
                    personSexTv.setText(userPage.getSex());
//                    //获得数据的objectId信息
//                    userPage.getObjectId();
//                    //获得createdAt数据创建时间（注意是：createdAt，不是createAt）
//                    userPage.getCreatedAt();
                    saveQB(userPage.getSex(), null, userPage.getNick_name());
                }
            }

            @Override
            public void onError(int i, String s) {
                Toast.makeText(PersonalDetailActivity.this, "获取信息失败" + s, Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.person_detail_icon:
                mDialog.popSelectDialog();
                break;
            case R.id.person_nickname:
                setPersonNick();
                break;
            case R.id.person_sex:
                setPersonSex();
                break;
            case R.id.back_btn:
                finish();
                break;

            case R.id.save_me:
                sex = personSexTv.getText().toString();
                nickName = personNickTv.getText().toString();
                saveUerData(sex, null, nickName);
                break;
            case R.id.my_two_dimension_code:
//                showMyTwoDimesionCode();
                Intent intent = new Intent(this, TwoDimensionCodeActivity.class);
                startActivity(intent);

                break;

        }
    }

    private void showMyTwoDimesionCode() {
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        ImageView imgView = getView();
        dialog.setView(imgView);
        dialog.show();
        // 全屏显示的方法
//         final Dialog dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
//         ImageView imgView = getView();
//         dialog.setContentView(imgView);
//         dialog.show();

        // 点击图片消失
        imgView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private ImageView getView() {
        ImageView imgView = new ImageView(this);
        imgView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        InputStream is = getResources().openRawResource(R.mipmap.chat_logo);//弹出的保存二维码
        Drawable drawable = BitmapDrawable.createFromStream(is, null);
        imgView.setImageDrawable(drawable);
        return imgView;
    }


    private void saveBmob() {

        //上传图片
        String path = OSUtils.getSdCardDirectory() + "/head.jpg";
        final BmobFile file = new BmobFile(new File(path)); //创建BmobFile对象，转换为Bmob对象
        file.upload(PersonalDetailActivity.this, new UploadFileListener() {
            @Override
            public void onSuccess() {
                PersonEntity userPage = new PersonEntity();
                userPage.setUsername(EMChatManager.getInstance().getCurrentUser());
                userPage.setSex(personSexTv.getText().toString());
                userPage.setNickName(personNickTv.getText().toString());
                userPage.setIcon(file);//设置图片
                Log.d("PersonalDetailActivity--+++++++>>>>", "运行到这里了");
                if (personNickTv.getText().toString() == null && personSexTv.getText().toString() == null) {
                    userPage.save(PersonalDetailActivity.this, new SaveListener() {
                        @Override
                        public void onSuccess() {
                            Toast.makeText(PersonalDetailActivity.this, "修改成功", Toast.LENGTH_SHORT).show();

                        }

                        @Override
                        public void onFailure(int i, String s) {
                            Toast.makeText(PersonalDetailActivity.this, "修改失败", Toast.LENGTH_SHORT).show();

                        }
                    });
                } else {
                    Toast.makeText(PersonalDetailActivity.this, "用户名与性别不能为空", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(int i, String s) {

            }
        });


    }

    private void saveUerData(String sex, String url, String nickName) {
        saveQB(sex, url, nickName);
        saveBmob();
    }

    private void saveQB(String sex, String url, String nickName) {

        qb.list().remove(EMChatManager.getInstance().getCurrentUser());
        UserPage data = new UserPage(EMChatManager.getInstance().getCurrentUser(), sex, null, nickName);
        AllSingleTon.getOurInstance().getDaoSession().getUserPageDao().insertOrReplace(data);
    }

    private void setPersonSex() {
        View view = LayoutInflater.from(this).inflate(R.layout.set_sex_layout, null);
        final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setView(view);
        dialog.setTitle("选择性别:");
        final TextView textViewMan, textViewWoman;
        textViewMan = (TextView) view.findViewById(R.id.sex_man);
        textViewWoman = (TextView) view.findViewById(R.id.sex_woman);

        textViewMan.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                textViewMan.setTextColor(Color.BLACK);
                textViewWoman.setTextColor(Color.GRAY);
                s = "b";


            }
        });
        textViewWoman.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                textViewWoman.setTextColor(Color.BLACK);
                textViewMan.setTextColor(Color.GRAY);
                s = null;
            }
        });
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (s == null) {
                    personSexTv.setText("女");
//                    sex = "女";
                } else {
                    personSexTv.setText("男");
//                    sex = "男";
                }

            }
        });
        dialog.setNegativeButton("取消", null);

        dialog.show();

    }

    private void setPersonNick() {
        View view = LayoutInflater.from(this).inflate(R.layout.set_nick_name_layout, null);
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("设置你的昵称");
        dialog.setView(view);
        final EditText editText;
        editText = (EditText) view.findViewById(R.id.write_nick_name);
        nickName = editText.getText().toString().trim();
        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                personNickTv.setText(editText.getText().toString());
                //TODO
                //和服务器判断是否重名
                waitDialog(nickName);
            }
        });
        dialog.setNegativeButton("取消", null);

        dialog.show();

    }

    private void waitDialog(String name) {


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        AllLruCacheLoad cacheLoad = new AllLruCacheLoad();
        if (requestCode == RESULT_CANCELED) {
            return;
        } else {
            switch (requestCode) {
                case CropHelper.HEAD_FROM_ALBUM:
                    mCropHelper.getDataFromAlbum(data);
                    Log.e("onActivityResult", "接收到图库图片");
                    break;
                case CropHelper.HEAD_FROM_CAMERA:
                    mCropHelper.getDataFromCamera(data);
                    Log.e("onActivityResult", "接收到拍照图片");
                    break;
                case CropHelper.HEAD_SAVE_PHOTO:
                    if (data != null && data.getParcelableExtra("data") != null) {
                        personDetailIcon.setImageBitmap((Bitmap) data.getParcelableExtra("data"));
                        mCropHelper.savePhoto(data, OSUtils.getSdCardDirectory() + "/myHead.png");
                        Log.d("PersonalDetailActivity----->>>>", "确定了照片");
//                        cacheLoad.putBitmap(OSUtils.getSdCardDirectory() + "/myHead.png",data);
                    }
                    break;

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
